package com.zzw;

import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * 模拟SpringApplication.run方法
 *
 * @Author: zhangzhiwei
 * @Date: 2022/1/3 23:59
 */
public class SpringApplication {

	static Logger log = LoggerFactory.getLogger(SpringApplication.class);

	public static void run(){

		// todo:创建tomcat并启动
		Tomcat tomcat = new Tomcat();
		tomcat.setBaseDir(createDir("tomcat"));
		Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
		connector.setPort(8888);
		tomcat.getService().addConnector(connector);
		tomcat.setConnector(connector);
		try {
			// 设置项目的访问路径
			tomcat.addWebapp("/", "D:\\");
			tomcat.start();
		} catch (Exception e) {
			log.error("Tomcat启动异常：" , e);
		}
		// 使tomcat处于阻塞状态
		tomcat.getServer().await();

	}

	public static String createDir(String fileName) {
		//File directory = new File("");// 参数为空
		try {
			String courseFile = System.getProperty("user.dir") + File.separator + fileName;
			File file = new File(courseFile);
			if (!file.exists()) {
				file.mkdirs();
			}
			return file.getAbsolutePath();
		} catch (Exception e) {
			log.error("创建Tomcat目录异常", e);
			return null;
		}
	}

}
